<template>
  <div class="v-flow-panel">
    <NodeWrap />
    <ConfigDrawer v-model="drawerVisible" />
  </div>
</template>

<script setup lang="ts">
import * as utils from './FlowPanel'
import * as configUtils from './configs/utils'
import type { NodeItem } from './types'
const emits = defineEmits(['update'])
const flowList = ref<NodeItem[]>([])
const flowTree = ref<NodeItem>()
const formList = ref<any[]>([])
const drawerVisible = ref<boolean>(false)
const currentNode = ref<NodeItem>()
provide('formData', {
  formList
})
provide('drawer', {
  currentNode,
  openDrawer: (node: NodeItem) => {
    drawerVisible.value = true
    currentNode.value = JSON.parse(JSON.stringify(node))
  }
})
provide('flowTree', {
  flowTree,
  flowList,
  // 新增节点
  addNode: (node: NodeItem) => {
    const parentNode = flowList.value.find((el: NodeItem) => {
      return el.nodeId === node.prevId
    })
    // 添加条件
    if (node.type === 3) {
      flowList.value = flowList.value.map((el: NodeItem) => {
        if (el.nodeId === node.prevId && el.conditionNodes && el.conditionNodes.length) {
          node.name = node.name + Number(el.conditionNodes.length + 1)
          el.conditionNodes = el.conditionNodes.concat(node)
        }
        return el
      })
    } else {
      // 在中间插入数据
      if (parentNode && parentNode.childNode) {
        flowList.value = flowList.value.map((el: NodeItem) => {
          if (el.nodeId === parentNode.childNode?.nodeId) {
            el.prevId = node.nodeId
            node.childNode = el
          }
          return el
        })
      }
      // 添加路由
      if (node.conditionNodes) {
        flowList.value = flowList.value.concat(node.conditionNodes)
      }
    }
    // formData
    if (!node.properties.formData) {
      return configUtils.initFormData(node.type, formList.value)
    }
    flowList.value.push(node)
    flowTree.value = utils.analysis(flowList.value)
    emits('update', flowTree.value)
  },
  editNode: (node: NodeItem) => {
    flowList.value = flowList.value.map((el: NodeItem) => {
      if (el.nodeId === node.nodeId) {
        return node
      } else {
        return el
      }
    })
    flowTree.value = utils.analysis(flowList.value)
    emits('update', flowTree.value)
  },
  removeNode: (node: NodeItem) => {
    flowList.value = utils.removeNode(flowList.value, node)
    flowTree.value = utils.analysis(flowList.value)
    emits('update', flowTree.value)
  }
})
defineExpose({
  // 新建
  init(tableForm: any, data: NodeItem) {
    formList.value = tableForm.forms
    if (data) {
      flowTree.value = JSON.parse(JSON.stringify(data))
    } else {
      flowTree.value = utils.initFlow()
    }
    if (flowTree.value) {
      flowList.value = utils.getList(flowTree.value)
    }
    return flowTree.value
  },
  updatedForms(tableForm: any) {
    formList.value = tableForm.forms
  }
})
</script>

<script lang="ts">
export default {
  name: 'VFlowPanel'
}
</script>

<style>
@import url(./FlowPanel.scss);
</style>
